<template>
  <UserTop @search="searchHandler" @add="addHandler" />
  <UserTabler :table-data="tableData" :current-page="currentPage" :page-size="pageSize" :total="total"
    @current-change="onCurrenChange" @size-change="onSizeChange" @edit="editHandler" @delete="deleteHandler" />
  <UserLog v-model="show" :dia-log="diaLog" @add="addUserHandler" @edit="editUserHandler" />
</template>
<script setup>
import UserLog from '@/components/user/UserLog.vue';
import UserTabler from '@/components/user/UserTabler.vue';
import UserTop from '@/components/user/UserTop.vue';
import { ref, reactive, watch } from 'vue';
import { getUserList, deleteUser, register, editUser } from '@/api/userApi'
// 表格数据
const tableData = ref([])
// 当前页
const currentPage = ref(1)
// 一页得数据
const pageSize = ref(5)
// 总条数
const total = ref(100)
// 控制对话框显示隐藏
const show = ref(false)
// 控制对话框是新增还是编辑
const diaLog = ref(null)
// 监听show的值关闭对话框时清空diaLog
watch(show, () => {
  if (!show.value) diaLog.value = null
})
// 表格渲染
init()
async function init(nickname = "", rolename = "", username = "") {
  const data = Object.assign({ pageCode: currentPage.value, pageSize: pageSize.value }, { nickname, rolename, username })
  const res = await getUserList(data)
  tableData.value = res.data
  total.value = res.total
}
// 搜索
async function searchHandler(data) {
  init(data.nickname, data.rolename, data.username)
}
// 新增
function addHandler() {
  show.value = true
}
// 点击切换当前页
function onCurrenChange(current) {
  currentPage.value = current
  init()
}
// 点击切换一页得数据
function onSizeChange(size) {
  pageSize.value = size
  init()
}
// 编辑
function editHandler(row) {
  show.value = true
  diaLog.value = row
}
// 删除
async function deleteHandler(row) {
  const res = await deleteUser({ id: row.id })
  if (res.code === 10000) {
    init()
  }
}
// 确认新增
async function addUserHandler(data) {
  const res = register(data)
  if (res.code === 10000) {
    init()
  }
}
// 确认编辑
async function editUserHandler(data) {
  const res = await editUser(data)
  if (res.code === 10000) {
    init()
  }
}
</script>
<style scoped></style>
